package com.bee.beemanage.system.aspect.aop;

import com.bee.beemanage.system.common.annotation.RedisCacheReload;
import com.bee.beemanage.system.common.utils.redis.RedisUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Component
public class RedisCacheReloadAspect {
    private final Logger logger = LoggerFactory.getLogger(ControllerLogAspect.class);
    @Resource
    RedisUtils redisUtils;
    /**
     * 切入点
     */
    @Pointcut("@annotation(com.bee.beemanage.system.common.annotation.RedisCacheReload)")
    public void pointCut(){

    }
    @Around("pointCut()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
        logger.info("----------- 缓存双删开始 -----------");
        logger.info("目标方法名：" + proceedingJoinPoint.getSignature().getName());

        Signature signature = proceedingJoinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method targetMethod = methodSignature.getMethod();//方法对象
        RedisCacheReload annotation = targetMethod.getAnnotation(RedisCacheReload.class);//反射得到自定义注解的方法对象
        String key = annotation.keyName();//获取自定义注解的方法对象的参数即name
        int delayT = annotation.delayTime();
        if(redisUtils.hasKey(key)){
            redisUtils.del(key);//模糊删除redis的key值
        }
        //执行加入双删注解的改动数据库的业务
        Object proceed = null;
        try {
            proceed = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        //开一个线程 在线程中延迟删除缓存
        new Thread(() -> {
            try {
                Thread.sleep(delayT);
                if(redisUtils.hasKey(key)){
                    redisUtils.del(key);//模糊删除redis的key值
                }
                logger.info("-----------"+delayT+"毫秒钟后，在线程中延迟删除完毕 -----------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        return proceed;
    }
}
